package com.songtech.login.controller;

import com.songtech.base.common.BaseConstant;
import com.songtech.base.common.JsonResult;
import com.songtech.login.model.SysPosUser;
import com.songtech.login.service.PLoginService;
import com.songtech.server.Jedis.JedisBaseDao;
import com.songtech.set.modle.TerminalInfo;
import com.songtech.set.service.TermianlInfoService;
import com.songtech.utils.MD5Util;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;

@Controller
public class PLoginController {
    private Logger logger = Logger.getLogger(PLoginController.class);

    @Autowired
    private PLoginService pLoginService;

    @Autowired
    private TermianlInfoService termianlInfoService;

    /**
     * 用户登录
     * @param request
     * @return*/
    @ResponseBody
    @RequestMapping(value="/plogin",method= RequestMethod.POST)
    public JsonResult login(HttpServletRequest request,String imei,String password) {
         logger.info("获取的参数imei:"+imei+"\npassword:"+password);
        try {
            password = MD5Util.encode(password);
        } catch (Exception e) {
            logger.error("密码转换失败:"+e.getMessage());
            e.printStackTrace();
        }
        JsonResult result = new JsonResult();
        HttpSession session = request.getSession();
        String loginOpenId = (String) session.getAttribute("openId");//获取openId
        SysPosUser user= pLoginService.getUser(imei);
        // 判断是否登录成功
        if(user == null){
            result.status = BaseConstant.FAIL_CODE;
            result.msg = "登录失败,设备账号有误";
        }else if(!password.equals(user.getPosUserPwd())){
            result.status = BaseConstant.FAIL_CODE;
            result.msg = "登录失败,密码错误";
        }else if(user != null && !StringUtils.isEmpty(loginOpenId)) {
            if(StringUtils.isEmpty(user.getOpenId()) || !loginOpenId.equals(user.getOpenId())){
                user.setOpenId(loginOpenId);
                if (pLoginService.updateUser(user) != 1) {
                    result.status = BaseConstant.FAIL_CODE;
                    result.msg = "用户登录失败";
                } else {
                    //登录成功,用户信息放入session中
                    session.setAttribute("loginUser", user);
                    result.status = BaseConstant.SUCCESS_CODE;
                    result.msg = "用户登录成功";
                }
            }else {
                //登录成功,用户信息放入session中
                session.setAttribute("loginUser", user);
                result.status = BaseConstant.SUCCESS_CODE;
                result.msg = "用户登录成功";
            }
        }else{
            result.status = BaseConstant.FAIL_CODE;
            result.msg = "用户登录失败";
        }
        logger.info("登录信息:"+result.msg);
        return result;
    }

    /**
     * system 登出
     * @param request
     * @return*/
    @RequestMapping(value="/plogout",method=RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        JsonResult result = new JsonResult();
        try {
            HttpSession session = request.getSession();
            String openId = (String) session.getAttribute("openId");
            if(StringUtils.isEmpty(openId)){
                return "redirect:/wechaTest.html";
            }
            logger.info("微信用户openid:"+openId);
            session.removeAttribute("openId");
            SysPosUser user = (SysPosUser) session.getAttribute("loginUser");
            if(user != null){
                user.setOpenId(null);
                pLoginService.updateUser(user);
                logger.info("删除数据成功");
                result.status=BaseConstant.SUCCESS_CODE;
                session.removeAttribute("loginUser");
                if(session.getAttribute("loginUser")==null && session.getAttribute("openId") == null){
                    logger.info("清除session成功");
                }else{
                    logger.info("清除session失败");
                }
            }
        } catch (Exception e) {
            result.status = BaseConstant.FAIL_CODE;
            e.printStackTrace();
            result.msg="退出失败，稍后再试";
        }
        logger.info("系统退出:"+result.msg);
        return "redirect:/wechaTest.html";
    }

    @RequestMapping(value="/location",method=RequestMethod.GET)
    public String realLocation() {
         return "redirect:/RealTimeLocation.html?v="+Math.random();
    }

    @RequestMapping(value="/deviceSetting",method=RequestMethod.GET)
    public String deviceSetting() {
        return "redirect:/Setting.html?v="+Math.random();
    }

    @RequestMapping(value="/deviceMessage",method=RequestMethod.GET)
    public String deviceMsg() {
        return "redirect:/EquipInfo.html?v="+Math.random();
    }

    @RequestMapping(value="/areaEditMap",method=RequestMethod.GET)
    public String areaEditMap() {
        return "redirect:/AreaEdit.html?v="+Math.random();
    }

    @RequestMapping(value="/historyTraces",method=RequestMethod.GET)
    public String historyTraces() {
        return "redirect:/HistoricalRoute.html?v="+Math.random();
    }

    @RequestMapping(value="/callUp",method=RequestMethod.GET)
    public String callUp(){
         return "redirect:/callup.html?v="+Math.random();
    }

    @ResponseBody
    @RequestMapping(value = "/modifyPassword",method = RequestMethod.POST)
    public JsonResult updatePwd(HttpServletRequest request,String oldPwd,String newPwd){
        JsonResult result = new JsonResult();
        HttpSession session = request.getSession();
        SysPosUser user = (SysPosUser) session.getAttribute("loginUser");
        try {
            oldPwd = MD5Util.encode(oldPwd);
            newPwd = MD5Util.encode(newPwd);
        } catch (Exception e) {
            logger.error("密码转换失败:"+e.getMessage());
            e.printStackTrace();
        }
        if(user == null){
            result.setStatus(BaseConstant.FAIL_CODE);
            result.setMsg("登录信息失效，稍后再试");
        }else if(!oldPwd.equals(user.getPosUserPwd())) {
            result.setStatus(BaseConstant.FAIL_CODE);
            result.setMsg("用户原密码错误，重新输入");
        }else{
            user.setPosUserPwd(newPwd);
            if (pLoginService.updatePwd(user)) {
                result.setStatus(BaseConstant.SUCCESS_CODE);
                result.setMsg(BaseConstant.SUCCESS);
            } else {
                result.setStatus(BaseConstant.FAIL_CODE);
                result.setMsg("修改密码失败，稍后再试");
            }
        }
        logger.info("修改密码:"+result.getMsg());
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/index",method = RequestMethod.POST)
    public JsonResult getIndex(HttpServletRequest request) throws SQLException {
        HttpSession session = request.getSession();
        JsonResult result = new JsonResult();
        SysPosUser user = (SysPosUser) session.getAttribute("loginUser");
        if(user == null){
            result.status = BaseConstant.FAIL_CODE;
            result.msg = "登录信息失效，稍后再试";
        }else{
            String imei = user.getImei();
            if(imei == null || "".equals(imei)){
                result.status = BaseConstant.FAIL_CODE;
                result.msg = "账号信息异常，稍后再试";
            }else {
                TerminalInfo terminalInfo = termianlInfoService.selectTerminalInfo(imei);
                if (terminalInfo == null) {
                    result.status = BaseConstant.FAIL_CODE;
                    result.msg = "设备异常，稍后再试";
                } else {
                    String terminalType = terminalInfo.getTerminalType();
                    if (terminalType == null || "".equals(terminalType)) {
                        result.status = BaseConstant.FAIL_CODE;
                        result.msg = "无此设备类型，稍后再试";
                    } else {
                        result.status = BaseConstant.SUCCESS_CODE;
                        result.msg = BaseConstant.SUCCESS;
                        result.data = terminalType;
                    }
                }
            }
        }
        logger.info("查询主页信息:"+result.msg);
        return result;
    }
}